﻿using Microsoft.Practices.ServiceLocation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace PlusAssistance.ControllerFactory
{
    public class StructureMapControllerFactory : DefaultControllerFactory
    {
        private readonly IServiceLocator _locator;
        private readonly IControllerFactory _innerFactory;

        public StructureMapControllerFactory(IServiceLocator locator)
            : this(locator, new DefaultControllerFactory())
        {

        }

        public StructureMapControllerFactory(IServiceLocator locator, IControllerFactory innerFactory)
        {
            _locator = locator;
            _innerFactory = innerFactory;
        }

        public override IController CreateController(RequestContext requestContext, string controllerName)
        {
            try
            {
                var controllerType = GetControllerType(requestContext, controllerName);

                if (controllerType != null)
                {
                    return _locator.GetInstance(controllerType) as IController;
                }

                return null;
            }
            catch (Exception)
            {
                return _innerFactory.CreateController(requestContext, controllerName);
            }
        }
    }
}